﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Threading.Tasks;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.Media.SpeechSynthesis;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using System.Net;
using System.Net.Http;
using HtmlAgilityPack;
using System.Text;
using Windows.ApplicationModel.Background;
using Windows.UI.Popups;
using Windows.Media.Playback;
using Windows.Media.Core;
using Windows.Storage.Pickers;
using Windows.Storage;
using Windows.Storage.Streams;
using static SuperTTS.TTS;
// https://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x804 上介绍了“空白页”项模板

namespace 小说阅读
{
    /// <summary>
    /// 可用于自身或导航至 Frame 内部的空白页。
    /// </summary>
    public sealed partial class MainPage : Page
    {
        private MediaElement mediaElement = new MediaElement();
        MediaPlayer _mediaPlayer;
        InMemoryRandomAccessStream imr;
        List<string> say_list = new List<string>();

        /// <summary>
        /// 最后的内容
        /// </summary>
        private string last_content = string.Empty;
        private string next_url { get; set; } = "";
        /// <summary>
        /// 章节地址
        /// </summary>
        private string zhangjie_url { get; set; } = "";
        private const string HOST = "https://www.xxbiquge.com/";
        public MainPage()
        {
            this.InitializeComponent();

            /*
          * */
            List<(string, int)> yy_list = new List<(string, int)>()
            {
                ("百合仙子" , 62060),
                ("小英", 65040),
                ("小薛" , 65320),
                ("伟香主" , 62070),
                ("四川方言" , 68060),
                ("东北话" , 68040),
                ("陕西方言" , 68080)
            };
            foreach (var p in yy_list)
            {
                yuyan_combox.Items.Add(new ComboBoxItem()
                {
                    Content = p.Item1,
                    Tag = p.Item2
                });
            }
            yuyan_combox.SelectedIndex = 0;

            Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
            //Init();
            url.Text = "https://www.xbiquge6.com/78_78513/125406.html";
            StandardPopup.Opened += StandardPopup_Opened;
            simple_list.SelectionChanged += Simple_list_SelectionChanged;
        }

        private void StandardPopup_Opened(object sender, object e)
        {
            simple_list.Width = (Window.Current.Bounds.Width / 2);
            simple_list.Height = Window.Current.Bounds.Height - 35;
            guanbi_btn.Width = simple_list.Width;
        }

        private async void Init()
        {
         


            var status = await BackgroundExecutionManager.RequestAccessAsync();
            if (status == BackgroundAccessStatus.Unspecified || status == BackgroundAccessStatus.Denied)
                await new MessageDialog("后台已被锁定").ShowAsync();
            bool isToastRegistered = false;
            string AlertToastTaskName = "Warframe_AlertToastTask";
            isToastRegistered = BackgroundTaskRegistration.AllTasks.Any(p => p.Value.Name == AlertToastTaskName);
            if (!isToastRegistered)
            {
                var builder = new BackgroundTaskBuilder
                {
                     Name=AlertToastTaskName,
                     TaskEntryPoint = "MyTask.TestTask",
                     IsNetworkRequested = true
                };
                TimeTrigger trigger = new TimeTrigger(2, false);
                builder.SetTrigger(trigger);
                BackgroundTaskRegistration task = builder.Register();
                await new MessageDialog("注册成功!").ShowAsync();
            }
        }

        private void Simple_list_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            var items = (ListBoxItem)((ListBox)sender).SelectedItem;
            string txt = items.Content.ToString();
            string url = items.Tag.ToString();
            next_url = url;
            GetNext();
            StandardPopup.IsOpen = false;
            //await new MessageDialog($"text:{items.Content} url:{items.Tag}").ShowAsync();
        }


        private async void ToPlay(string msg)
        {
            say_list.Clear();
            if (_mediaPlayer != null)
            {
                _mediaPlayer.Dispose();
                _mediaPlayer = null;
            }
            if(imr!=null)
            {
                imr.Dispose();
                imr = null;
            }


            //切割所有内容到列表
            StringBuilder sb = new StringBuilder();
            int num = 0;
            for (int i = 0; i < msg.Length; i++)
            {
                num++;
                var v = msg.Substring(i,1);
                sb.Append(v);
                switch (v)
                {
                    case ".":
                    case "。":
                    case "!":
                    case "！":
                    case "?":
                    case "？":
                    //case ",":
                    //case "，":
                        num = 0;
                        say_list.Add(sb.ToString());
                        sb.Clear();
                        break;
                    default:
                        if(num>180)
                        {
                            num = 0;
                            say_list.Add(sb.ToString());
                            sb.Clear();
                        }
                        break;
                }
            }
            if(sb.Length>0)
            {
                say_list.Add(sb.ToString());
                sb.Clear();
            }

            using (imr = new InMemoryRandomAccessStream())
            {
                //主动去获取声音
                //foreach (var p in say_list)
                {
                    var say_ren = (int)(yuyan_combox.SelectedItem as ComboBoxItem).Tag;
                    int speed = 0;
                    if (kuai_su.IsChecked==true)
                        speed = 500;
                    var bytes = await SuperTTS.TTS.GetPlayBytes(say_list.ToArray(), (VID_ENUM)say_ren, 0, speed, new Action<(int allcount, int make_num, int make_bytes)>(async (r)=> {
                       await mytext.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Low, () =>
                        {
                            mytext.Text = $"正在加载声音(共{r.allcount} 已处理{r.make_num}个 {r.make_bytes}字节)";
                            if (r.allcount == r.make_num)
                            {
                                mytext.Text = last_content;
                            }
                        });

                    }));
                    _mediaPlayer = new MediaPlayer();
                    await imr.WriteAsync(bytes.AsBuffer());
                    _mediaPlayer.Source = MediaSource.CreateFromStream(imr, "audio/mpeg");
                    _mediaPlayer.Play();

                }
            }

        }
        private void Button_Click(object sender, RoutedEventArgs e)
        {
  


            if (!string.IsNullOrEmpty(url.Text))
            {

                next_url = url.Text.Trim();
            }
            ((Button)sender).IsEnabled = false;
            
            mediaElement.MediaEnded += MediaElement_MediaEnded;
            GetNext(true);
        }

        private void MediaElement_MediaEnded(object sender, RoutedEventArgs e)
        {
            GetNext();
        }

        private async void GetNext(bool flag=false)
        {
            try
            {
                string html = await GetHtml(next_url);
                HtmlAgilityPack.HtmlDocument doc = new HtmlDocument();
                doc.LoadHtml(html);
                title.Text = doc.DocumentNode.SelectSingleNode("//h1").InnerText;
                //解析内容
                var node = doc.DocumentNode.SelectSingleNode("//div[@id='content']");
                string content = node.InnerText;
                content = content.Replace("&nbsp;", "");

                if(flag)
                {
                    //获取章节地址
                    var t_list = doc.DocumentNode.SelectNodes("//a").Where(x => x.InnerText == "章节列表").ToList();
                    //var t_list = doc.DocumentNode.SelectNodes("//a[@id='pager_current']");

                    if (t_list.Count > 0)
                    {
                        zhangjie_url = HOST + t_list[0].GetAttributeValue("href", string.Empty);
                        if (!string.IsNullOrEmpty(zhangjie_url))
                        {
                            //解析章节列表
                            //获取章节列表数据
                            var zj_html = await GetHtml(zhangjie_url);
                            if (!string.IsNullOrEmpty(zj_html))
                            {
                                simple_list.Items.Clear();
                                //解析章节列表
                                var _zj_hd_doc = new HtmlDocument();
                                _zj_hd_doc.LoadHtml(zj_html);
                                var nodes_list = _zj_hd_doc.DocumentNode.SelectNodes("//div[@id='list']//a");
                                //var nodes_list = _zj_hd_doc.DocumentNode.SelectNodes("//div[@class='listmain']//a");

                                await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Low, () =>
                                {

                                    foreach (var p in nodes_list)
                                    {
                                        string txt = p.InnerText;
                                        string url = p.Attributes["href"].Value;
                                        url = url.StartsWith("http") ? url : HOST + url;
                                        simple_list.Items.Add(new ListBoxItem()
                                        {
                                            Tag = url,
                                            Content = txt
                                        });
                                    }
                                    show_menu.IsEnabled = true;
                                });
                            }

                        }
                    }
                }


                var list = doc.DocumentNode.SelectNodes("//a").Where(x => x.InnerText == "下一章").ToList();
                //var list = doc.DocumentNode.SelectNodes("//a[@id='pager_next']");


                if (list.Count > 0)
                {
                    string _mynext = list[0].GetAttributeValue("href", string.Empty);
                    if (!string.IsNullOrEmpty(_mynext))
                    {
                        next_url = HOST + _mynext;
                        next_btn.IsEnabled = true;

                    }
                    else
                    {
                        next_btn.IsEnabled = false;
                    }
                }
                else
                {
                    next_btn.IsEnabled = false;
                }
                last_content = content;
                //播放
                ReadAsync(content);
            }
            catch (Exception ex)
            {
                MessageDialog dialog = new MessageDialog(ex.Message);
                await dialog.ShowAsync();
                next_btn.IsEnabled = true;
            }
            finally
            {
                url.Text = next_url;
            }
        }

        /// <summary>
        /// 获取html
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        private async Task<string> GetHtml(string url)
        {
            string html = string.Empty;
            using (HttpClient hc = new HttpClient())
            {
                
                var stream = await hc.GetStreamAsync(url);
                using(StreamReader sr = new StreamReader(stream, System.Text.Encoding.UTF8))
                {
                    html = await sr.ReadToEndAsync();
                }

            }
            return html;
        }

        private void ReadAsync(string text)
        {

            ToPlay(text);
            //using (var synth = new SpeechSynthesizer())
            //{
            //    // Generate the audio stream from plain text.
            //    using (SpeechSynthesisStream stream = await synth.SynthesizeTextToStreamAsync(text))
            //    {

            //        // Send the stream to the media object.
            //        mediaElement.SetSource(stream, stream.ContentType);
            //        mediaElement.Play();
            //    }
            //}
        }

        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            GetNext();
        }

        private void Button_Click_2(object sender, RoutedEventArgs e)
        {
            StandardPopup.IsOpen = false;
        }

        private void show_menu_Click(object sender, RoutedEventArgs e)
        {
            StandardPopup.IsOpen = true;
        }
    }
}
